<?php
final class Query
{
	private $accepted_types = array('select', 'insert', 'update', 'delete');

	private $type 		= NULL;
	private $manual		= NULL;
	private $table 		= NULL;
	private $dataColumn 	= NULL;
	private $dataValue 	= NULL;

	private $where 		= array();

	private $orderBy 	= NULL;
	private $limit 		= NULL;

	public function __construct() {}

	public function type($f_type)
	{
		$f_type = strtolower($f_type);

		$this->type = in_array($f_type, $this->accepted_types) ? $f_type : 'insert';

		return $this;
	}

	public function table($f_table)
	{
		$this->table = (string) $f_table;
	
		return $this;
	}

	public function data(array $f_data)
	{
		$this->dataColumn = array_keys($f_data);
		$this->dataValue  = array_values($f_data);

		return $this;
	}

	public function where(array $f_where, $f_operator = '=')
	{
		$this->where  = $f_where[0];
		$this->where .= chr(32);
		$this->where .= $f_operator;
		$this->where .= chr(32);
		$this->where .= (is_numeric($f_where[1])) ? (int) $f_where[1] : "'{$f_where[1]}'";

		return $this;
	}

	public function orderBy($f_orderBy)
	{
		$this->orderBy = (string) $f_orderBy;

		return $this;
	}

	public function limit($f_limit_start, $f_limit_end = FALSE)
	{
		$this->limit = $f_limit_start;
		
		if($f_limit_end)
		{
			$this->limit .= ", {$f_limit_end}";
		}
		
		return $this;
	}

	public function create()
	{
		static $query;

		switch ($this->type) 
		{ 
			case 'select':
				$query  = 'SELECT ';
				$query .= implode(', ', $this->dataValue);
				$query .= " FROM {$this->table}";

				if( ! empty($this->where) )
				{
					$query .= " WHERE {$this->where}";
				}

				if( ! empty($this->orderBy) )
				{
					$query .= " ORDER BY {$this->orderBy}";
				}

				if( ! empty($this->limit) )
				{
					$query .= " LIMIT {$this->limit}";
				}

				break; 

			case 'insert':
				$query  = "INSERT INTO {$this->table} ("; 
                 		$query .= implode(', ', $this->dataColumn);
				$query .= ') VALUES (\'';
				$query .= implode('\', \'', $this->dataValue);
				$query .= '\')';
				break;

			case 'delete':
				$query = "DELETE FROM {$this->table}";

				if( ! empty($this->where) )
				{
					$query .= " WHERE {$this->where}";
				}

				break;

			case 'update':
				$query = "UPDATE {$this->table} SET";

				$combine = array_combine($this->dataColumn, $this->dataValue);

				$i = 0;

				foreach($combine as $key => $value)
				{
					$query .= ($i == 0) ? chr(32) : ', ';
					$query .= "{$key} = ";
					$query .= (is_numeric($value)) ? $value : "'{$value}'";

					++$i;
				}

				if( ! empty($this->where) )
				{
					$query .= " WHERE {$this->where}";
				}

				break;
		}

		return $query;
	}
}

?>